import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:spendbook/common/constants.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/bankCard.dart';
import 'package:spendbook/models/family.dart';
import 'package:spendbook/models/user.dart';

class DepositScreen extends StatefulWidget {
  DepositScreen({Key? key}) : super(key: key);

  @override
  _DepositScreenState createState() => _DepositScreenState();
}

class _DepositScreenState extends State<DepositScreen> {
  final List<BankCard> _cards = [];
  String _current = '筛选';
  RefreshController _refreshController = RefreshController();
  int? _uid;
  int _loaded = 0;

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _refreshController.requestRefresh();
    });
  }

  Future _getList() async {
    List _list = await BankCard().fetch(_uid == null ? null : {'uid': _uid.toString()});
    if (mounted) {
      setState(() {
        _cards.clear();
        _list.forEach((_item) => _cards.add(BankCard()..fromJson(_item)));
        _loaded = 1;
      });
    }
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    final _user = context.read<User>();

    return Scaffold(
      appBar: AppBar(title: Text('我的存款'), actions: <Widget>[
        TextButton(
          style: Theme.of(context).useMaterial3 ? null : TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onPrimary),
          onPressed: () async {
            await selectFamily(
                context: context,
                onSubmit: (Family family) async {
                  setState(() {
                    _current = family.nickname;
                  });
                  _uid = family.family!.id;
                  _refreshController.requestRefresh();
                },
                onCancel: () async {
                  setState(() {
                    _current = '筛选';
                  });
                  _uid = null;
                  _refreshController.requestRefresh();
                });
          },
          child: Text(
            _current,
            style: TextStyle(fontSize: 16),
          ),
        ),
      ]),
      body: SmartRefresher(
        controller: _refreshController,
        onRefresh: _getList,
        child: ListView.builder(
            padding: const EdgeInsets.only(left: 5, right: 5, bottom: 60),
            itemCount: _cards.length > 0 ? _cards.length : _loaded,
            itemBuilder: (BuildContext context, int index) {
              if (_cards.isEmpty) return NoData();
              final BankCard _card = _cards[index];
              return Card(
                  child: ListTile(
                title: Text(_card.bank),
                subtitle: Text('存款余额: ' + toStringAsMoney(_card.fee)),
                trailing: _user.id == _card.user!.id
                    ? PopupMenuButton(
                        padding: EdgeInsets.all(0.0),
                        offset: Offset.zero,
                        child: Icon(Icons.more_vert),
                        itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                          const PopupMenuItem<String>(
                            value: 'setting',
                            child: Text('设置'),
                          ),
                          const PopupMenuItem<String>(
                            value: 'delete',
                            child: Text('删除'),
                          ),
                        ],
                        onSelected: (String selected) async {
                          if (selected == 'setting') {
                            final _newCard = await Navigator.pushNamed(context, '/deposit/set', arguments: _card.toJson()) as BankCard?;
                            if (_newCard != null) {
                              setState(() {
                                _cards[index] = _newCard;
                              });
                            }
                          } else if (selected == 'delete') {
                            final res = await showOkCancelAlertDialog(context: context, title: '确定删除?', message: '确定要删除该银行卡吗?');
                            if (res == OkCancelResult.ok) {
                              await _card.delete();
                              setState(() {
                                _cards.removeAt(index);
                              });
                            }
                          }
                        },
                      )
                    : null,
              ));
            }),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          final _card = await Navigator.pushNamed(context, '/deposit/add') as BankCard?;
          if (_card != null) {
            setState(() {
              _cards.insert(0, _card);
            });
          }
        },
      ),
    );
  }
}
